const http = require('http')
const url = require('url')
const Redis = require("ioredis")
const redis = new Redis(6379, '127.0.0.1')

class Server {
  constructor() {
    this.config = {
      port: 3000
    }
  }

  start() {
    const server = http.createServer(this.serveHandle.bind(this))
    server.listen(this.config.port, () => {
      console.log(`服务启动了 ---> http://localhost:${this.config.port}`)
    })
  }

  async serveHandle(req, res) {
    const { method } = req
    let { pathname, query } = url.parse(req.url, true)
    pathname = decodeURIComponent(pathname)

    try {
      // 打捞一个漂流瓶
      if (pathname === '/get-drifting-bottle') {
        const { user, type } = query
        if (method === 'GET') {
          const ret = await redis.hgetall(`hash-${user}`)

          if (ret) {
            res.writeHead(200, { 'Content-Type': 'application/json' })
            res.end(JSON.stringify({
              "code": 1,
              "msg": ret
            }))
          } else {
            throw new Error()
          }
        } else {
          throw new Error()
        }

        return
      }

      // 扔出一个漂流瓶
      if (pathname === '/throw-drifting-bottle') {
        if (method === 'POST') {
          const { owner, type, content, time } = query
          if (owner && type && content) {
            // 存为hash
            await redis.hset(`hash-${owner}`, {
              "time": time || Date.now(),
              "owner": owner,
              "type": type,
              "content": content
            })

            res.writeHead(200, { 'Content-Type': 'application/json' })
            res.end(JSON.stringify({
              "code": 1,
              "msg": "漂流瓶已扔出"
            }))
          } else {
            res.writeHead(200, { 'Content-Type': 'application/json' })
            res.end(JSON.stringify({
              "code": 1,
              "msg": "参数有误"
            }))
          }
        } else {
          throw new Error()
        }
        return
      }

      throw new Error()
    } catch (err) {
      this.errorHandle(req, res, err)
    }
  }

  errorHandle(req, res, err) {
    res.writeHead(200, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({ "code": 0, "msg": "失败了" }))
  }
}

new Server().start()
